import pymysql

# pymysql使用步骤 1.连接 2.游标 3.执行查询指令，命令 4.关闭资源 5.结束
def creat_table():
    db = pymysql.connect(host='49.233.39.160', port = 3306, user = 'user', password = 'leboAa!#$123', db = 'lebo16')
    cursor = db.cursor()

    cursor.execute('drop table  if EXISTS kkd;')
    sql = """create table kkd( 
    id int unsigned primary key auto_increment,
    name varchar(20),
    age int unsigned);"""

    try:
        # 执行sql语句
        cursor.execute(sql)
        print('数据表创建success')
    except Exception as e:
        print('数据表创建fail，原因:%s' % e)
    finally:
        db.close()

# 增加数据方法
def insert_table():
    db = pymysql.connect(host = '49.233.39.160', port = 3306, user = 'user', password = 'leboAa!#$123', db = 'lebo16')
    cursor = db.cursor()

    sql = """
    insert into kkd values
    ('王昭君',20),
    ('诸葛亮',20),
    ('孙尚香',20);
    """
    try:
        cursor.execute(sql)
        # 事务
        db.commit()
        print('数据表新增数据success')
    except Exception as e:
        print('插入数据失败，原因：%s' % e)
        db.rollback()
    finally:
        db.close()

#   creat_table()
insert_table()